package com.hao.gaoji;
// 测试Lock锁

import java.util.concurrent.locks.ReentrantLock;

public class testLock {
    public static void main(String[] args) {
        TestLock1 testLock = new TestLock1();
        for (int i = 0; i < 3; i++) {
            new Thread(testLock).start();
        }
    }
}

class TestLock1 implements Runnable{
    int ticketNums = 10;

    // 定义Lock
   private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock(); // 加锁
                if (ticketNums>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                }else {
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}
